import { TreePSD } from 'psd';
import { FileFactory } from 'lite-ts-fs';

import { Sprite } from './cc';
import { ConverterBase } from './base';
import { enum_ } from '../../model';

export class SlicedSpriteConverter extends ConverterBase {
    public static prefix = 'simg';

    public async convert() {
        const psdChild = this.treePSD.children()
        let mainPsd: TreePSD = psdChild[0];
        let deputyPsd: TreePSD = psdChild[1];
        if (mainPsd.get<string>(enum_.Psd.name).split('-').length <= 1)
            [mainPsd, deputyPsd] = [deputyPsd, mainPsd];

        const info = mainPsd.get<string>(enum_.Psd.name).split('-');
        const get = mainPsd.get.bind(mainPsd);
        mainPsd.get = prop => {
            return prop == 'name' ? deputyPsd.get(enum_.Psd.name) : get(prop);
        };
        
        const mainName = mainPsd.get<string>(enum_.Psd.name);
        const node = this.createNode({ name: mainName });
        const sprite = await this.appendSprite(mainPsd, node);
        sprite.type = Sprite.Type.SLICED;

        const texturePathMate = `texture/${mainName}.png.meta`;
        const factory = new FileFactory().buildFile(this.fileFactory.cwd, this.fileFactory.view, texturePathMate);
        const data = await factory.read<{
            subMetas: {
                borderTop: number,
                borderBottom: number,
                borderLeft: number,
                borderRight: number
            }
        }>();
        const subMetas: any = Object.values(data.subMetas)[1];
        subMetas.userData.borderTop = +info[0];
        subMetas.userData.borderBottom = +info[1];
        subMetas.userData.borderLeft = +info[2];
        subMetas.userData.borderRight = +info[3];
        await factory.write(JSON.stringify(data));
        return node;
    }
}